package presenters;

import java.sql.ResultSet;
import java.sql.SQLException;

import model.ConnectionManager;
import model.DbSchema;
import model.IPresenter;
import views.PaymentInfoPanel;
import views.PersonInfoPanel;

public class PaymentInfoPresenter extends IPresenter {
	private PaymentInfoPanel myPanel;
	private PersonInfoPanel myParentPanel;

	public PaymentInfoPresenter(PaymentInfoPanel p) {
		super();
		myPanel = p;
	}
	
	public void populateFields(String cardNo) {
		String sql = "SELECT * FROM " + ConnectionManager.GROUP
				+ ".CREDIT_CARD WHERE CARD_NO = '" + cardNo + "';";
		ResultSet rs = executeSQLQuery(sql);
		
		try {
			rs.first();
			String card_No = rs.getString("CARD_NO");
			String cardName = rs.getString("NAME_ON_CARD");
			String billing = rs.getString("BILLING_ADDRESS");
			String expir = rs.getString("EXPIR_DT");
			String cvv = rs.getString("CVV");
			
			myPanel.setFields(cardName, card_No, cvv, expir, billing);
		}
		catch(SQLException e) {
			e.printStackTrace();
		}
	}

	public int updatePayment(String nameOnCard, String cardNum, String cvv,
			String experDate, String billingAddress) {

		int out = -1;
		if (checkString2(nameOnCard) && checkString(cardNum)
				&& checkString(cvv) && checkString2(billingAddress)) {
			
			String sqlUpdate = "IF (SELECT COUNT(*) "
					+ "FROM " + ConnectionManager.GROUP + ".CREDIT_CARD "
					+ "WHERE CARD_NO = '" + cardNum + "' "
					+ "GROUP BY CARD_NO "
				+ " IS NULL) THEN "
					+ "INSERT INTO CREDIT_CARD(CARD_NO, NAME_ON_CARD, BILLING_ADDRESS, EXPIR_DT, CVV)"
					+ " VALUES('"
					+ cardNum 			+ "', '"
					+ nameOnCard 		+ "', '"
					+ billingAddress 	+ "', '"
					+ experDate 		+ "', '"
					+ cvv 				+ "');" 
				+ " ELSE "
					+ " UPDATE CREDIT_CARD "
						+ "SET "
						+ "NAME_ON_CARD = '" + nameOnCard + "', "
						+ "BILLING_ADDRESS = '" + billingAddress + "', "
						+ "EXPIR_DT = '" + experDate + "', "
						+ "CVV = '" + cvv + "' "
						+ "WHERE (CARD_NO = '" + cardNum + "');";
			
			
			/*String sqlUpdate = "UPDATE INTO " + ConnectionManager.GROUP + "." 
			+ DbSchema.CC_TABLE + "("
					+ DbSchema.CC_NUM + ", "
					+ DbSchema.CC_NAME + ", "
					+ DbSchema.CC_BILL_ADD + ", "
					+ DbSchema.CC_EXPRDATE + ", "
					+ DbSchema.CC_CVV + ")"
					+ " VALUES('"
						+ cardNum 			+ "', '"
						+ nameOnCard 		+ "', '"
						+ billingAddress 	+ "', '"
						+ experDate 		+ "', '"
						+ cvv 				+ "');"; */
			
			out = executeSQLUpdate(sqlUpdate);
			System.out.println("Card added at row: " + out);
		} // close check if
		return out;
	} // close method
} // close class
